﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Linq;
using Abp.Reflection.Extensions;

namespace GCT.Foundation.Helpers
{
    public class FoundationTemplateWebContentDirectoryFinder
    {
        public static string CalculateContentRootFolder()
        {
            var coreAssemblyDirectoryPath = Path.GetDirectoryName(typeof(FoundationTemplateCoreModule).GetAssembly().Location);
            if (coreAssemblyDirectoryPath == null)
            {
                throw new Exception("找不到程序集 GCT.Foundation.Template.Core !");
            }

            // sln
            var directoryInfo = new DirectoryInfo(coreAssemblyDirectoryPath);
            while (!DirectoryContains(directoryInfo.FullName, "GCT.Foundation.Template.sln"))
            {
                directoryInfo = directoryInfo.Parent ?? throw new Exception("找不到项目根目录!");
            }

            // webhost
            var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "GCT.Foundation.Template.Web.Host");
            if (!Directory.Exists(webHostFolder))
            {
                throw new Exception("无法找到web项目的根文件夹!");
            }

            Console.WriteLine("当前使用 GCT.Foundation.Template.Web.Host 项目启动");
            return webHostFolder;

        }

        private static bool DirectoryContains(string directory, string fileName)
        {
            return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName));
        }
    }
}
